import selenium.webdriver.chrome.webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By

from bean.hot_new import HotNew
from typing import List
import traceback
from news_platform.plat.web_platform import WebPlatform

app_path = 'pages/article/detail/detail?id={0}&type=article&city=bj'


class BenDiBao(WebPlatform):

    def __init__(self):
        self.name = "本地宝资讯"

    def query_hot_news(self) -> List[HotNew]:
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--start-maximized")
        chrome_options.add_argument("--no-sandbox")
        browser = webdriver.Chrome(options=chrome_options)
        # browser.get("http://jtapi.bendibao.com/tianqi/api/getweatherbox/new.aspx?citycode=bj&domain=bj.bendibao.com")
        try:
            browser.set_page_load_timeout(10)
            browser.get("http://bj.bendibao.com/")
            browser.implicitly_wait(10)
            # browser.get("http://bj.bendibao.com/")
            # browser.switch_to.window(browser.window_handles[1])
            result = self.generate_news(browser)
        except Exception as e:
            print(e)
            print(traceback.format_exc())
            result = self.generate_news(browser)
        browser.quit()
        return result

    def generate_news(self, browser: selenium.webdriver.chrome.webdriver.WebDriver):
        result: List[HotNew] = []
        class_ele_list = browser.find_elements(By.CLASS_NAME, "focus-news")
        serial_no = 0
        for class_data_ele in class_ele_list:
            data_ele_list = class_data_ele.find_elements(By.TAG_NAME, "a")
            for data_ele in data_ele_list:
                serial_no = serial_no + 1
                title = data_ele.text
                link = data_ele.get_attribute("href")
                excerpt = ''
                hot_new = HotNew(serial_no, title, link, "4", "", excerpt)
                result.append(hot_new)
        for hotNew in result:
            link: str = hotNew.link
            app_path_id = link[link.rindex("/") + 1: link.rindex(".")]
            try:
                browser.get(link)
                # browser.switch_to.window(browser.window_handles[1])
                excerpt_div_list = browser.find_elements(By.CLASS_NAME, 'leading')
                if len(excerpt_div_list) > 0:
                    hotNew.excerpt = excerpt_div_list[0].text.replace('【导语】：', '')
                    hotNew.app_path = app_path.format(app_path_id)
            except Exception as e:
                print(e)
                print(traceback.format_exc())
        return result
